package model

import (
	"global/structs"
	"time"
	"fmt"
)

const (
	BACKUP_CONFIG_TYPE = "system"
	BACKUP_CONFIG_KEY = "backup_db_num"

	DEFAULT_BACKUP_DB_NUM = "1"
)

type systemConfigModel struct {}

var SystemCoinfigModel = new(systemConfigModel)

// 获取备份表
func (self systemConfigModel) GetBackupDBConfig() (string, error) {
	config := new(structs.SystemConfig)
	has, err := MainDB.Where("`type`=? AND `key`=?", BACKUP_CONFIG_TYPE, BACKUP_CONFIG_KEY).Get(config)
	if err != nil {
		return "", err
	}
	if !has {
		_, err := self.createBackupDBConfigItem()
		if err != nil {
			return "", err
		}
		return DEFAULT_BACKUP_DB_NUM, nil
	}
	return config.Value, nil
}

// 修改配置
func (systemConfigModel) UpdateValue(num int) error {
	config := new(structs.SystemConfig)
	config.Value = fmt.Sprintf("%d", num)
	config.UpdateTime = time.Now()
	row, err := MainDB.Where("`type`=? AND `key`=?", BACKUP_CONFIG_TYPE, BACKUP_CONFIG_KEY).Cols("value", "update_time").Update(config)
	if err != nil {
		return err
	}
	if row > 0 {
		return nil
	}
	return fmt.Errorf("nothing changed")
}

// 创建一行记录
func (systemConfigModel) createBackupDBConfigItem() (bool, error) {
	config := &structs.SystemConfig{
		Type: 		BACKUP_CONFIG_TYPE,
		Key: 		BACKUP_CONFIG_KEY,
		Title: 		"委托单备份记录表",
		Value: 		DEFAULT_BACKUP_DB_NUM,
		Enabled: 	"1",
		CreateTime: time.Now(),
		UpdateTime: time.Now(),
	}
	rows, err := MainDB.Insert(config)
	if err != nil {
		return false, err
	}
	return rows > 0, nil
}